package com.advert.presentation.bean;

import com.advert.config.Config;
import com.advert.model.advert.AdvertEntity;
import com.advert.model.advert.search.AdvertStatusCriteria;
import com.advert.model.security.Role;
import com.advert.model.security.Status;
import com.advert.model.security.UserEntity;
import com.advert.presentation.util.ActionOutcome;
import com.advert.service.admin.AdminService;
import com.advert.service.advert.AdvertService;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import java.util.List;

@Name("adminBean")
@Scope(ScopeType.PAGE)
public class AdminBean extends PageAwareBeanBase {
    @In("AdminService")
    private AdminService adminService;
    @In("AdvertService")
    private AdvertService advertService;
    @In("config")
    private Config config;

    private String role;
    private Integer pageCount;
    private List<UserEntity> users;
    private List<AdvertEntity> adverts;


    // Accessors
    
    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public List<UserEntity> getUsers() {
        if (users == null) {
            if (getRole() != null) {
                Role role = null;
                try {
                    role = Role.valueOf(getRole());
                } catch (IllegalArgumentException e) {}
                if (role != null) {
                    users = adminService.getUsersByRole(role);
                }
            }
        }
        return users;
    }

    public List<AdvertEntity> getAdverts() {
        if (adverts == null) {
            adverts = advertService.getAdverts(new AdvertStatusCriteria(Status.PENDING), getPageNumber(), getAdvertsToDisplay());
        }
        return adverts;
    }

    public int getPageCount() {
        if (pageCount == null) {
            pageCount = advertService.getPageCount(new AdvertStatusCriteria(Status.PENDING), getAdvertsToDisplay());
        }
        return pageCount;
    }


    // Actions

    public void updateUserRoles() {
        adminService.updateUsersRole(users);    
    }

    public String approveAdvert(AdvertEntity advert) {
        advert.setRejectReason(null);
        adminService.approveAdvert(advert);

        return ActionOutcome.APPROVED.name();
    }

    public String rejectAdvert(AdvertEntity advert) {
        adminService.rejectAdvert(advert);

        return ActionOutcome.REJECTED.name();
    }

}
